# coding: UTF-8
# @Date    ：2024/10/14 17:52 
# @File    : __init__.py
# :Author:  fum
import os
from typing import Optional, Dict, Any

from pydantic_settings import SettingsConfigDict

from .system import SystemConfig
from .system.db_config import DatabaseConfigSettings
from .system.system_config import SystemConfigSettings
from ..libs import PrintUtils
from ..libs.path import PathUtil


class Settings(
    SystemConfig,
):
    """所有配置 优先使用环境变量映射配置 其次使用配置文件映射配置"""
    model_config = SettingsConfigDict(
        env_file=PathUtil.get_env(),
        env_file_encoding="utf-8",
        frozen=True,
        # ignore allow forbid    允许未定义的字段
        extra="allow",
        # case sensitive 默认False 大小写铭感
        case_sensitive=True,
    )


# 存储全局配置对象
CONFIG: Optional[dict[str, any]] = None


class ConfigManager:
    def __init__(self):
        self.config: Optional[Dict[str, Any]] = None
        self.init_config()

    def set_config(self, dic: Dict[str, Any]):
        """添加其他配置"""
        if self.config is None:
            self.config = {}
        for key, value in dic.items():
            self.config.setdefault(key, value)

    def init_config(self):
        """初始化配置"""
        config_dict = self.init_config_config()
        self.init_os_config(config_dict)
        PrintUtils.print_colored(f"配置初始化成功 : 【{PathUtil.get_env()}】")
        PrintUtils.print_fancy_data([self.config], "CONFIG")
        return self

    def init_config_config(self):  # CONFIG
        """初始化纯配置"""
        all_config = Settings()
        config_dict = all_config.model_dump()
        global CONFIG
        self.config = config_dict
        CONFIG = config_dict
        return config_dict

    def init_os_config(self, config_dict: Dict[str, Any]):  # OS
        """加载配置到os.environ"""
        for key, value in config_dict.items():
            if key.endswith("_DIR"):
                os.makedirs(value, exist_ok=True)
            if isinstance(value, str):
                os.environ[key] = value
            elif isinstance(value, (int, float, bool)):
                os.environ[key] = str(value)
            elif value is None:
                os.environ[key] = ""

    def get_config(self) -> Dict[str, Any]:
        """获取当前的配置"""
        return self.config
